package com.zivwu.library.rx.subscriber;


import com.orhanobut.logger.Logger;
import com.zivwu.library.exception.ApiException;
import com.zivwu.library.widget.progress.ProgressListener;
import com.zivwu.library.interfaces.ToastListener;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.net.SocketTimeoutException;

/**
 *  快速处理net返回的数据
 * @param <T>
 */
public class ErrorSubscriber<T> implements Subscriber<T> {


    protected ToastListener toastListener;
    private ProgressListener.Visible progressListener;

    public ErrorSubscriber(ToastListener toastListener) {
        this(toastListener, null);
    }

    public ErrorSubscriber(ToastListener toastListener, ProgressListener.Visible progressListener) {
        this.toastListener = toastListener;
        this.progressListener = progressListener;
    }


    @Override
    public void onError(Throwable e) {
        if (progressListener != null)
            progressListener.removeProgress();
        if (e instanceof ApiException) {
            //API 返回错误
            if (toastListener != null)
                toastListener.showToast(e.getMessage());
        } else if (e instanceof SocketTimeoutException) {
            if (toastListener != null)
                toastListener.showToast("网络连接超时，请检查");
        } else if (e instanceof IllegalStateException) {
            Logger.e(e.getMessage());
        }
    }

    @Override
    public void onNext(T t) {

    }

    @Override
    public void onSubscribe(Subscription s) {
        if (progressListener != null)
            progressListener.showProgress();

    }

    @Override
    public void onComplete() {
        if (progressListener != null)
            progressListener.removeProgress();
    }

}

